<?php


namespace App\Application\Services\Application;

use App\Application\Middleware\ApplicationApiHttpAuthMiddleware;
use App\Models\Application\Application;
use App\Repositories\Application\ApplicationRepository;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ApplicationService {
    /**
     * 判断提供的app信息是否正确
     *
     * @param $appId
     * @param $appKey
     *
     * @return mixed
     * @throws \App\Exceptions\RepositoryException
     */
    public static function checkAppAuth($appId, $appKey, &$appEl = null) {
        $appRep = new ApplicationRepository();
        $appEl  = $appRep->getApplicationByAppId($appId);
        
        return self::_checkAppAuth($appKey, $appEl);
    }
    
    /**
     * 获取第三方操作依赖的应用信息
     * @return Application
     */
    public static function getAuthAppInfo() {
        return app()->make(ApplicationApiHttpAuthMiddleware::APP_CONTAINER_NAME);
    }
    
    /**
     * 检验验证信息
     *
     * @param                   $appKeyHashWithTime
     * @param Application|null  $appEl
     *
     * @return bool
     */
    private static function _checkAppAuth($appKey, $appEl) {
        
        /** @var Application $appEl */
        if (!$appEl) {
            throw new HttpException(401, '应用不存在');
        }
        
        if (!$appEl->secret_key) {
            throw new HttpException(401, '应用秘钥设置错误，请联系管理员正确配置');
        }
        
        if (!($appEl->secret_key == $appKey)) {
            throw new HttpException(401, '秘钥验证错误');
        }
        
        return true;
    }
}